<template>
  <div class="sms">
    <div class="back">
      <el-link
        v-if="state == 2"
        type="primary"
        @click="
          () => {
            state = 1
            entity.code = ''
          }
        "
        >上一步</el-link
      >
    </div>

    <h1>邮箱验证码</h1>
    <el-form ref="dataForm" :rules="formRules" :model="entity">
      <div v-if="state == 1">
        <el-form-item prop="email">
          <j-input-wrapper>
            <el-input
              ref="emailInput"
              v-model="entity.email"
              @keyup.enter="showCaptchaHandler"
              placeholder="邮箱地址"
            />
          </j-input-wrapper>
        </el-form-item>

        <br />
        <el-button
          type="primary"
          @click="showCaptchaHandler"
          :loading="smsLoading"
          >发送验证码</el-button
        >
      </div>

      <div v-else>
        <p>
          已向邮箱<span>&nbsp;{{ entity.email }}</span>
        </p>
        <p>发送验证码，请填写</p>
        <br />

        <el-form-item prop="code">
          <password-input
            v-loading="loginLoading"
            ref="passwordInput"
            :value="entity.code"
            :length="6"
            :mask="false"
            :gutter="1"
            :focused="focused"
            @click="passwordInputClickHandler"
          />
        </el-form-item>
        <el-button
          type="text"
          @click="showCaptchaHandler"
          :loading="smsLoading"
        >
          {{ stateText }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { sendEmailSms, smsLogin } from '@/api/login'
import { PasswordInput } from 'vant'

export default {
  name: 'Sms',
  emits: ['captcha', 'login-success'],
  data() {
    return {
      entity: {
        email: '',
        code: '',
        smsType: 'login',
        userType: 'ADMIN',
      },
      formRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
        ],
      },
      state: 1,
      smsLoading: false,
      loginLoading: false,
      seconds: 60,
      interval: null,
      focused: false,
    }
  },
  computed: {
    stateText() {
      let resend = '重新发送'
      if (this.seconds != 60) {
        resend = resend + '（' + this.seconds + '）'
      }
      return resend
    },
  },
  components: {
    PasswordInput,
  },
  beforeUnmount() {
    if (this.interval) clearInterval(this.interval)
  },
  methods: {
    showCaptchaHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$emit('captcha', this.verifySuccessHandler)
        }
      })
    },
    verifySuccessHandler(captchaVerification) {
      this.smsLoading = true

      let data = Object.assign(this.entity, captchaVerification)
      sendEmailSms(data)
        .then((res) => {
          this.entity.ticket = res.data.data
          this.$message.success('发送成功')

          this.state = 2
          this.passwordInputClickHandler()

          this.interval = setInterval(() => {
            if (this.seconds == 0) {
              clearInterval(this.interval)
              this.interval = null
              this.seconds = 60
            } else {
              this.seconds--
            }
          }, 1000)
        })
        .finally(() => {
          this.smsLoading = false
        })
    },
    smsLoginHandler() {
      if (!this.entity.code) {
        this.$message.error('请输入验证码')
        return
      }

      this.loginLoading = true
      smsLogin(this.entity)
        .then(() => {
          this.$message.success('登录成功')
          this.$emit('login-success')
        })
        .finally(() => {
          this.loginLoading = false
        })
    },
    passwordInputClickHandler() {
      if (this.focused) {
        return
      }

      this.focused = true
      let numberInputListener = (e) => {
        if (e.keyCode >= 48 && e.keyCode <= 57) {
          this.entity.code = this.entity.code + (e.keyCode - 48)
        } else if (e.keyCode == 8) {
          if (this.entity.code.length > 0) {
            this.entity.code = this.entity.code.substr(
              0,
              this.entity.code.length - 1
            )
          }
        }

        if (this.entity.code.length == 6) {
          this.smsLoginHandler()
        }
      }
      document.addEventListener('keydown', numberInputListener)

      setTimeout(() => {
        document.onclick = (e) => {
          let passwordInput = this.$refs.passwordInput.$el
          if (e.target == passwordInput) {
            return
          }

          let parent = e.target.parentElement
          while (parent != null) {
            if (parent == passwordInput) {
              return
            } else {
              parent = parent.parentElement
            }
          }

          this.focused = false
          document.removeEventListener('keydown', numberInputListener)
        }
      }, 100)
    },
  },
}
</script>
<style lang="scss">
.sms {
  position: relative;
  height: 100%;

  .back {
    position: absolute;
    top: 15px;
    left: 20px;
  }

  .van-password-input {
    width: 100%;
    margin: 0;
  }

  p {
    color: #909399;
    text-align: center;
    margin-bottom: 2px;

    span {
      color: #409eff;
    }
  }
}
</style>
